package com.gp.controller.goods;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gp.common.result.JsonResult;
import com.gp.common.utils.CookieUtils;
import com.gp.controller.BaseController;
import com.gp.model.dto.ItemInfo;
import com.gp.model.entity.BaseUser;
import com.gp.service.IBaseCartService;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;

/**
 * @author: 弓成龙
 * @date : 2017年12月19日
 * @email : gcx909109@sina.cn
 * @description: 购物车控制层
 */
@RestController
@Api(description = "购物车", value = "购物车")
@RequestMapping(value = "/cart")
public class CartController extends BaseController{
  @Autowired
  private IBaseCartService cartService;

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  @ApiOperation(value = "添加单个商品到购物车")
  public JsonResult addCart(HttpServletRequest request, HttpServletResponse response,
      @Validated ItemInfo itemInfo, BindingResult bindingResult) {
    boolean result = cartService.addCartItem(request, response, itemInfo);
    return result ? new JsonResult("添加成功", result) : new JsonResult("添加失败", result);
  }

  @RequestMapping(value = "/list", method = RequestMethod.GET)
  @ApiOperation(value = "获取购物车商品列表", httpMethod = "GET",
      notes = "如果用户已经登录，从数据库中获取")
  public JsonResult getCartList(HttpServletRequest request) {
    List<ItemInfo> list = cartService.selectAll(request);
    return new JsonResult("获取成功", list);
  }

  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  @ApiOperation(value = "编辑购物车商品", notes = "编辑用户商品到购物车")
  public JsonResult updateCartItem(ItemInfo itemInfo,HttpServletRequest reqeust) {
    boolean result = cartService.updateByUserID(itemInfo,reqeust);
    return result ? new JsonResult("修改成功", result) : new JsonResult("修改失败", result);
  }

  @RequestMapping(value = "/del/{goodsid}", method = RequestMethod.POST)
  @ApiOperation(value = "删除购物车商品",notes="如果用户已经登录了的话，删除数据库中的购物车的商品，如果没有登录的话，从cookies中删除")
  public JsonResult deleteCartItem(HttpServletRequest request,@PathVariable Long goodsid) {
	if (! CookieUtils.isExistsCurrentUser(request)) return renderError("用户不存在");
	boolean result = cartService.deleteCartItem(((BaseUser)CookieUtils.obtainCurrentUser(request)).getId(), goodsid);
    return result ? new JsonResult("删除成功", result) : new JsonResult("删除失败", result);
  }
}

